<?php

namespace addons\third\library;

use addons\third\model\Third;
use app\common\model\User;
use fast\Random;
use think\Db;
use think\exception\PDOException;
use think\Config;

/**
 * 第三方登录服务类
 *
 * @author Karson
 */
class Service
{

    /**
     * 第三方登录
     * @param string $platform 平台
     * @param array  $params   参数
     * @param array  $extend   会员扩展信息
     * @param int    $keeptime 有效时长
     * @return boolean
     */
    public static function connect($platform, $params = [], $extend = [], $keeptime = 0)
    {
        $time = time();

        if(array_key_exists('access_token', $params)){
            $values = [
                'platform'      => $platform,
                'openid'        => $params['openid'],
                'access_token'  => $params['access_token'],
                'expires_in'    => 0,
                'logintime'     => $time,
                'expiretime'    => $time,
            ];
        }else{
            $values = [
                'platform'      => $platform,
                'openid'        => $params['openid'],
                'openname'      => isset($params['nickname']) ? $params['nickname'] : '',
                'logintime'     => $time,
                'expiretime'    => $time,
            ];
        }
        
        $auth = \app\common\library\Auth::instance();

        $auth->keeptime($keeptime);
        $third = Third::get(['platform' => $platform, 'openid' => $params['openid']]);
        if ($third) {
            $user = User::get($third['user_id']);
            if (!$user) {
                return false;
            }else{
                
                $extend['prevtime'] = $time;

                $user->allowField(true)->save($extend);
            }
            $third->save($values);
            return $auth->direct($user->id);
        } else {

            // 先随机一个用户名,随后再变更为u+数字id
            $username = Random::alnum(20);
            $password = Random::alnum(6);
            $domain = request()->host();

            Db::startTrans();
            try {
               // 默认注册一个会员
                // 在user表创建一条新用户数据
                if(array_key_exists('nickname', $params)){
                    $username = $params['nickname'];
                    $extend = $params;
                    $extend['avatar'] = $params['headimgurl'];
                }else{
                    $extend = ['gender' => 0, 'nickname' => '', 'avatar' => Config('site.cdnurl').'\assets\img\avatar.png'];
                }

                $result = $auth->register($username, $password, $username . '@' . $domain, '', $extend, $keeptime);

                if (!$result) {
                    return false;
                }
                $user = $auth->getUser();
                if(array_key_exists('nickname', $params)){
                    $fields = ['nickname'=>$params['nickname'],'username' => $params['nickname'], 'email' => 'u' . $user->id . '@' . $domain];
                }else{
                    $fields = ['nickname'=>'u' . $user->id,'username' => 'u' . $user->id, 'email' => 'u' . $user->id . '@' . $domain];
                }

                // 更新会员资料
                $user = User::get($user->id);

                Db::name('collect')->insert(['user_id'=>$user->id]);
                Db::name('dianzan')->insert(['user_id'=>$user->id]);

                if($params['Invitees']){
                    $fields['Invitees'] = $params['Invitees'];//记录是谁邀请你的

                    // 给邀请人的 invitation_num 加一
                    Db::name('user')->where('id',$params['Invitees'])->setInc('invitation_num');

                    // 修改 tui_user_id 邀请过的user_id 
                    $Invitees_data = Db::name('user')->where('id',$params['Invitees'])->find();
                    $new_tui_user_id = $params['Invitees'].','.$Invitees_data['tui_user_id'];

                    Db::name('user')->where('id',$params['Invitees'])->update(['tui_user_id'=>$new_tui_user_id]);
                }

                $usersave_res = $user->save($fields);
             
                // 保存第三方信息
                // 在third表插入一条新用户数据
                $values['user_id'] = $user->id;
                if(array_key_exists('nickname', $params)){
                    $values['openname'] = $params['nickname'];
                }else{
                    $values['openname'] = 'u' . $user->id;
                }
                Third::create($values);
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $auth->logout();
                return false;
            }

            // 写入登录Cookies和Token
            return $auth->direct($user->id);
        }
    }
}
